"""
Score system for tank battle game
"""
import json
import os
import sys
from typing import Dict, List, Optional

# Add src directory to path for imports
current_dir = os.path.dirname(os.path.abspath(__file__))
src_dir = os.path.dirname(current_dir)
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from utils.constants import TankType


class ScoreSystem:
    """Score management system"""
    
    def __init__(self):
        """Initialize score system"""
        self.current_score = 0
        self.high_scores = []
        self.score_file = "high_scores.json"
        self.max_high_scores = 10
        
        # Score multipliers
        self.score_multipliers = {
            TankType.ENEMY_BASIC: 100,
            TankType.ENEMY_FAST: 150,
            TankType.ENEMY_HEAVY: 200
        }
        
        # Load high scores
        self._load_high_scores()
    
    def _load_high_scores(self):
        """Load high scores from file"""
        if os.path.exists(self.score_file):
            try:
                with open(self.score_file, 'r') as f:
                    self.high_scores = json.load(f)
            except (json.JSONDecodeError, IOError):
                self.high_scores = []
        else:
            self.high_scores = []
    
    def _save_high_scores(self):
        """Save high scores to file"""
        try:
            with open(self.score_file, 'w') as f:
                json.dump(self.high_scores, f)
        except IOError:
            pass  # Fail silently if can't save
    
    def add_score(self, points: int, reason: str = ""):
        """
        Add points to current score
        
        Args:
            points: Points to add
            reason: Reason for scoring (for debugging)
        """
        self.current_score += points
    
    def get_enemy_score(self, tank_type: str) -> int:
        """
        Get score for destroying enemy tank
        
        Args:
            tank_type: Type of enemy tank
            
        Returns:
            Score points for destroying this tank type
        """
        return self.score_multipliers.get(tank_type, 100)
    
    def destroy_enemy(self, tank_type: str) -> int:
        """
        Add score for destroying enemy tank
        
        Args:
            tank_type: Type of enemy tank destroyed
            
        Returns:
            Points awarded
        """
        points = self.get_enemy_score(tank_type)
        self.add_score(points, f"Destroyed {tank_type}")
        return points
    
    def get_current_score(self) -> int:
        """Get current score"""
        return self.current_score
    
    def reset_score(self):
        """Reset current score to 0"""
        self.current_score = 0
    
    def is_high_score(self) -> bool:
        """Check if current score is a high score"""
        if len(self.high_scores) < self.max_high_scores:
            return True
        
        lowest_high_score = min(score['score'] for score in self.high_scores)
        return self.current_score > lowest_high_score
    
    def add_high_score(self, player_name: str = "Player") -> bool:
        """
        Add current score to high scores
        
        Args:
            player_name: Name of player
            
        Returns:
            True if score was added
        """
        if not self.is_high_score():
            return False
        
        # Add new high score
        new_score = {
            'name': player_name,
            'score': self.current_score,
            'date': self._get_current_date()
        }
        
        self.high_scores.append(new_score)
        
        # Sort by score (highest first)
        self.high_scores.sort(key=lambda x: x['score'], reverse=True)
        
        # Keep only top scores
        if len(self.high_scores) > self.max_high_scores:
            self.high_scores = self.high_scores[:self.max_high_scores]
        
        # Save to file
        self._save_high_scores()
        
        return True
    
    def _get_current_date(self) -> str:
        """Get current date as string"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M")
    
    def get_high_scores(self) -> List[Dict]:
        """Get list of high scores"""
        return self.high_scores.copy()
    
    def get_top_score(self) -> Optional[Dict]:
        """Get the highest score"""
        if self.high_scores:
            return self.high_scores[0]
        return None
    
    def clear_high_scores(self):
        """Clear all high scores"""
        self.high_scores = []
        self._save_high_scores()
    
    def get_score_breakdown(self) -> Dict[str, int]:
        """Get breakdown of score sources"""
        return {
            'current_score': self.current_score,
            'high_score': self.get_top_score()['score'] if self.get_top_score() else 0,
            'enemy_basic': self.score_multipliers[TankType.ENEMY_BASIC],
            'enemy_fast': self.score_multipliers[TankType.ENEMY_FAST],
            'enemy_heavy': self.score_multipliers[TankType.ENEMY_HEAVY]
        }
